package com.yjck.ijpay.utils.wxutils;

import com.yjck.ijpay.utils.AjaxDone;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 
 ****************************************************************************
 * Copyright (C) 2017 河南坚磐电子科技有限公司 All Rights Reserved
 ****************************************************************************
 * 【编写时间】 2018年7月12日 【编 写 人】 韩川 【功能概要】 微信支付统一下单，验签工具类
 ****************************************************************************
 *
 */

public class WXPayUtils {

	/**
	 * 微信支付统一下单
	 * 
	 * @param request
	 *            请求的HttpServletRequest
	 * @param order_no
	 *            订单号
	 * @param content
	 *            订单内容
	 * @param amount
	 *            订单金额
	 * @param openId
	 *            微信openId
	 * @param noticeUrl
	 *            异步回调Url
	 * @return
	 * @throws Exception
	 *             初始化配置文件异常
	 */


	public static String getIpAddr(HttpServletRequest request) {
	    String ip = request.getHeader("x-forwarded-for"); 
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	      ip = request.getHeader("Proxy-Client-IP"); 
	    } 
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	      ip = request.getHeader("WL-Proxy-Client-IP"); 
	    } 
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	      ip = request.getRemoteAddr(); 
	    } 
	    return ip; 
	  }

	public static AjaxDone wxH5ToPay(HttpServletRequest request, String order_no, String content, int amount,
									 String openId, String noticeUrl) throws Exception {
		AjaxDone result = new AjaxDone();

		String appId = ""; //#小程序
		String mchId = "mchid"; //#商户号
		String Notify_url = "wechatNotify_url";//	https：//www.baidu.com/payResult.do  UNIFIED_ORDER_URL=//https：//www.baidu.com/
		String APPKey = "appkey"; //#小程序key
		String UNIFIED_ORDER_URL = "UNIFIED_ORDER_URL"; //https://api.mch.weixin.qq.com/pay/unifiedorder  统一下单api
		String charset = "wechatCHARSET"; //wechatCHARSET=UTF-8

		// 生成微信预支付订单
		JsPayResult jsPayResult = null;
		String spbill_create_ip = "spbill_create_ip";// 客户端IP
		
//		String spbill_create_ip = getIpAddr(request);
		
//		System.out.println("spbill_create_ip:"+spbill_create_ip);
		
		String nonce_str = MsgUtil.createNonceStr(); // 随机数据
		// 参数组装
		UnifiedOrderParams unifiedOrderParams = new UnifiedOrderParams();
		unifiedOrderParams.setAppid(appId);// 必须
		unifiedOrderParams.setMch_id(mchId);// 必须
		unifiedOrderParams.setNonce_str(nonce_str); // 必须
		unifiedOrderParams.setBody(content);// 必须
		unifiedOrderParams.setOut_trade_no(order_no);// 必须
		unifiedOrderParams.setTotal_fee(amount); // 必须
		unifiedOrderParams.setSpbill_create_ip(spbill_create_ip); // 必须
		unifiedOrderParams.setNotify_url(Notify_url + noticeUrl);// 异步通知url
		unifiedOrderParams.setTrade_type("JSAPI"); // 必须
		unifiedOrderParams.setOpenid(openId);

		// 统一下单 请求的Xml(正常的xml格式)
		String unifiedXmL = MsgUtil.abstractPayToXml(unifiedOrderParams, APPKey);// 签名并入util
		System.out.println("统一下单 请求的Xml==="+unifiedXmL);
		// 返回<![CDATA[SUCCESS]]>格式的XML
		String unifiedOrderResultXmL = WXHttpUtil.HttpsDefaultExecute("POST", UNIFIED_ORDER_URL, null, unifiedXmL,
				null);

		// 进行签名校验
		if (SignatureUtil.checkIsSignValidFromWeiXin(unifiedOrderResultXmL, APPKey, null)) {
			String timeStamp = DateUtil.createTimeStamp();
			// 统一下单响应
			UnifiedOrderResult unifiedOrderResult = XmlUtil.getObjectFromXML(unifiedOrderResultXmL,
					UnifiedOrderResult.class);
			jsPayResult = new JsPayResult();
			jsPayResult.setAppId(appId);
			jsPayResult.setTimeStamp(timeStamp);
			jsPayResult.setNonceStr(unifiedOrderResult.getNonce_str());// 直接用返回的
			/**** prepay_id 2小时内都有效，再次支付方法自己重写 ****/
			jsPayResult.setPackageStr("prepay_id=" + unifiedOrderResult.getPrepay_id());
			/**** 用对象进行签名 ****/
			String paySign = SignatureUtil.createSign(jsPayResult, APPKey, charset);
			jsPayResult.setPaySign(paySign);
			jsPayResult.setResultCode(unifiedOrderResult.getResult_code());
			result.setStatusCode("200");
			result.setMessage("支付成功");
			result.setModel(jsPayResult);
			System.out.println("统一下单响应=="+unifiedOrderResult);
		} else {
			result.setStatusCode("201");
			result.setMessage("支付签名验证错误");
		}
		return result;
	}

	/**
	 * 微信异步回调验签
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public static PayNotifyResult wxNoticeUrlResult(HttpServletRequest request) throws Exception {
		String inputLine;
		String notityXml = ""; // 微信返回xml
		// 微信给返回的东西
		try {
			while ((inputLine = request.getReader().readLine()) != null) {
				notityXml += inputLine;
			}
			request.getReader().close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (!StringUtils.isEmpty(notityXml)) {
			//需要从配置读取
			String APPKey = "wechatAPPkey";
			if (SignatureUtil.checkIsSignValidFromWeiXin(notityXml, APPKey, null)) {
				// 解析返回xml
				PayNotifyResult objectFromXML = XmlUtil.getObjectFromXML(notityXml, PayNotifyResult.class);
				return objectFromXML;
			}
		}
		return null;
	}

	public static Map<String, String> xmlToMap(String strXML) throws Exception {
		Map<String, String> data = new HashMap();
		DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
		InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
		Document doc = documentBuilder.parse(stream);
		doc.getDocumentElement().normalize();
		NodeList nodeList = doc.getDocumentElement().getChildNodes();

		for(int idx = 0; idx < nodeList.getLength(); ++idx) {
			Node node = nodeList.item(idx);
			if (node.getNodeType() == 1) {
				Element element = (Element)node;
				data.put(element.getNodeName(), element.getTextContent());
			}
		}

		try {
			stream.close();
		} catch (Exception var10) {
		}

		return data;
	}


	public static String sendGet(String url, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : map.keySet()) {
				System.out.println(key + "--->" + map.get(key));
			}
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}


}
